"""
核心数据处理与计算逻辑（核心接口示例）

提供：
- load_data(cfg=None, filename=None): 从 config.yaml 指定的 data_path 加载 csv 或 dta 文件，返回 pandas.DataFrame
"""
from pathlib import Path
from typing import Optional

import pandas as pd
import yaml


def load_data(cfg: Optional[dict] = None, filename: Optional[str] = None) -> pd.DataFrame:
	"""Load a dataset from data directory defined in cfg or config.yaml.

	Args:
		cfg: optional dict loaded from config.yaml (if None, function will try to read config.yaml from repo root)
		filename: optional filename under data/ (if not provided, will try to use cfg['csv_path'] or raise)

	Returns:
		pandas.DataFrame

	Raises:
		FileNotFoundError: if target file is not found
		ValueError: if file format not supported
	"""
	# locate config
	if cfg is None:
		repo_root = Path(__file__).resolve().parents[1]
		cfg_path = repo_root / 'config.yaml'
		if not cfg_path.exists():
			raise FileNotFoundError('config.yaml not found and no cfg provided')
		with cfg_path.open('r', encoding='utf-8') as f:
			cfg = yaml.safe_load(f) or {}

	repo_root = Path(__file__).resolve().parents[1]
	data_path = Path(cfg.get('data_path', 'data'))
	# normalize data_path to be under repo root
	if not data_path.is_absolute():
		data_path = (repo_root / data_path).resolve()

	# determine filename
	if filename is None:
		filename = cfg.get('csv_path') or cfg.get('data_file')
		if filename is None:
			raise ValueError('No filename provided and no csv_path/data_file in config')

	filename_path = Path(filename)
	# Resolve candidate target carefully:
	if filename_path.is_absolute():
		target = filename_path
	else:
		# If filename already contains a directory component (e.g., data/your.csv),
		# resolve relative to repo root and check if it's under data_path.
		candidate = (repo_root / filename_path).resolve()
		if str(candidate).startswith(str(data_path)):
			target = candidate
		elif filename_path.parent != Path('.'):
			# filename contains subdirectory but not the data_path; treat as repo-relative
			target = candidate
		else:
			# plain filename: place under data_path
			target = (data_path / filename_path).resolve()
	if not target.exists():
		raise FileNotFoundError(f"Data file not found: {target}")

	suf = target.suffix.lower()
	if suf == '.csv':
		return pd.read_csv(target)
	elif suf == '.dta':
		return pd.read_stata(target)
	else:
		raise ValueError('Unsupported data format: ' + suf)


def run_simple_ols(df: pd.DataFrame, y_col: str, x_cols: list):
	"""Run a simple OLS regression using statsmodels.

	Args:
		df: pandas DataFrame
		y_col: dependent variable column name
		x_cols: list of independent variable column names

	Returns:
		statsmodels RegressionResults (fitted)
	"""
	try:
		import statsmodels.api as sm
	except Exception as e:
		raise ImportError('statsmodels is required for run_simple_ols') from e

	X = df[x_cols].copy()
	X = sm.add_constant(X)
	y = df[y_col]
	model = sm.OLS(y, X)
	results = model.fit()
	return results
# 回归与导出逻辑已移至 examples/ 目录中的示例脚本（如需恢复，请查看 examples/core_example.py）

